/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.vendas.sistema.util;

import com.vendas.sistema.util.HibernateUtil;
import java.io.IOException;
import javax*;
import javax.servlet.*;
import org.hibernate.SessionFactory;

/**
 *
 * @author leandro
 */
public class conexaoHibernateFilter implements Filter {
    
    private SessionFactory sf ;
    
    @Override
    public void init(FilterConfig config)throws ServletException
    {
       this.sf=HibernateUtil.getSessionFactory();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    {
        try
       {
        this.sf.getCurrentSession().beginTransaction();
        chain.doFilter(request, response);
        this.sf.getCurrentSession().getTransaction().commit();
        this.sf.getCurrentSession().close();
        }catch(Throwable ex)
        {
            try
            {
                if(this.sf.getCurrentSession().getTransaction().isActive())
                {
                    this.sf.getCurrentSession().close();
                }
                
                catch(Throwable t)
                        {
                        t.printStackTrace();
                        }
            }
                 throw new ServletException(ex);       
        }  
        }

    @Override
    public void destroy() {
        
    }
}